package _18_剑指OfferII;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class _015_剑指OfferII字符串中的所有变位词 {

    public List<Integer> findAnagrams(String s, String p) {
        int len1 = s.length();
        int len2 = p.length();
        List<Integer> results = new ArrayList<>();
        if (len1 < len2) return results;
        char[] chars1 = s.toCharArray();
        char[] chars2 = p.toCharArray();
        int[] map1 = new int[26];
        int[] map2 = new int[26];
        for (char c : chars2) {
            map2[c - 'a']++;
        }

        // 滑动比较s2的值
        for (int i = 0; i < len2; i++) {
            map1[chars1[i] - 'a']++;
        }
        if (Arrays.equals(map1, map2)) results.add(0);

        // 窗口滑动
        for (int i = len2; i < len1; i++) {
            map1[chars1[i - len2] - 'a']--;
            map1[chars1[i] - 'a']++;
            if (Arrays.equals(map1, map2)) results.add(i - len2 + 1);
        }
        return results;
    }

}
